package jaux.tank.service.system.impl;


import java.util.List;
import java.util.Optional;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jaux.tank.admin.config.properties.TankProperties;
import jaux.tank.bean.core.ShiroUser;
import jaux.tank.bean.entity.system.User;
import jaux.tank.bean.exception.ParamException;
import jaux.tank.bean.exception.TankException;
import jaux.tank.bean.exception.ValidException;
import jaux.tank.bean.vo.UserInfo;
import jaux.tank.bean.vo.UserSettings;
import jaux.tank.bean.vo.front.Rets;
import jaux.tank.dao.cache.LoginIdCache;
import jaux.tank.dao.cache.TokenCache;
import jaux.tank.dao.system.UserRepository;
import jaux.tank.factory.UserFactory;
import jaux.tank.platform.log.LogManager;
import jaux.tank.platform.log.LogTaskFactory;
import jaux.tank.service.system.AccountService;
import jaux.tank.utils.CryptUtils;
import jaux.tank.utils.HttpKit;
import jaux.tank.utils.Lists;
import jaux.tank.utils.ObjectId;

/**
 * AccountServiceImpl
 *
 * @author zt
 * @version 2018/9/12 0012
 */
@Service
public class AccountServiceImpl implements AccountService {
	
	
	private static final String LOGIN_ID_FAILURE = "登录会话无效";
    @Autowired
    private TokenCache tokenCache;
    @Autowired
    LoginIdCache loginIdCache;
    @Autowired
    TankProperties tankProps;
    @Autowired
    private UserRepository userRepository;
    @Override
    public String login(String idUser) {
        Optional<User> userOpt = userRepository.findById(idUser);
        if(!userOpt.isPresent()) {
        	return null;
        }
        User user = userOpt.get();
        String token = UUID.randomUUID().toString();
        tokenCache.put(token, idUser);
        LogManager.me().executeLog(LogTaskFactory.loginLogWithUserAgent(idUser, HttpKit.getIp(), HttpKit.getUserAgent()));
        String[] roleArray = user.getRoleid().split(",");
        ShiroUser shiroUser = new ShiroUser();
        shiroUser.setAccount(user.getAccount());
        HttpSession session = HttpKit.getRequest().getSession();
		shiroUser.setSessionId(session.getId());
        shiroUser.setDeptId(user.getDeptid());
        shiroUser.setDeptName(ConstantFactory.me().getDeptName(user.getDeptid()));
        shiroUser.setId(idUser);
        shiroUser.setName(user.getName());
        shiroUser.setRoleList(Lists.newArrayList(roleArray));
        List<String> roleNames = Lists.newArrayList();
        List<String> roleCodes = Lists.newArrayList();
        for (String roleId : roleArray) {
            roleCodes.add(ConstantFactory.me().getSingleRoleTip(roleId));
            roleNames.add(ConstantFactory.me().getSingleRoleName(roleId));

        }
        shiroUser.setRoleNames(roleNames);
        shiroUser.setRoleCodes(roleCodes);
        session.setAttribute("shiroUser", shiroUser);
        session.setAttribute("loginPath", HttpKit.getRequest().getRequestURI());
        session.setAttribute("userAgent", HttpKit.getUserAgent());
        tokenCache.setUser(token,shiroUser);
        return token;
    }

    @Override
    public String validLoginIdAndPassword(String loginId, String password) {
    	// 删除登录id
    	boolean loginIdAvaliable = false;
    	if(loginId !=null) {
    		loginIdAvaliable =loginIdCache.get(loginId);
    		loginIdCache.remove(loginId);
    	}
    	// 是否开启验证登录会话有效性
    	if((tankProps.isLoginPasswdEncrypted()||tankProps.isValidLoginId()) && !loginIdAvaliable) {
    		throw new ValidException(LOGIN_ID_FAILURE);
    	}
    	// 判断是否开启了登录密码加密
    	if(tankProps.isLoginPasswdEncrypted()) {
    		password = CryptUtils.decode(password, loginId);
    	}
    	return password;
    }
    @Override
    public String getLoginId() {
    	String loginId = ObjectId.get().toHexString();
    	loginIdCache.put(loginId);
    	return loginId;
    }
    
    @Override
    public void logout(String token) {
        tokenCache.remove(token);
    }
    @Override
    public User update(String userId, UserSettings settings) {
    	Optional<User> optionalUser = userRepository.findById(userId);
    	if(optionalUser.isPresent()) {
	    	User user = UserFactory.updateUser(settings, optionalUser.get());
    		return userRepository.save(user);
    	}else {
	    	return null;
    	}
    }
    
}
